package com.jiangmiao.babaisyou.util;

import com.jiangmiao.babaisyou.constant.MapConstant;
import com.jiangmiao.babaisyou.ui.GameFrame;

import javax.swing.*;
import java.awt.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 游戏所需工具
 */
public class GameUtil {
    /**
     * 根据 url 加载图片
     * @param url
     * @return
     */
    public static Image loadBufferedImage(String url) {
        URL resource = GameFrame.class.getResource(url);
        Image image = new ImageIcon(resource).getImage();
        return image;
    }

    /**
     * 加载地图文件
     *
     * @param url
     * @return
     */
    public static Map<String, Object> loadMap(String url) throws IOException {
        Map<String, Object> res = new HashMap<>();
        Map<String, Location> text = new HashMap<>();
        Map<String, List<Location>> people = new HashMap<>();


        res.put(MapConstant.TEXT, text);
        res.put(MapConstant.PEOPLE, people);


        URL resource = GameFrame.class.getResource(url);

        InputStream resourceAsStream = GameFrame.class.getResourceAsStream(url);

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(resourceAsStream));
        String line = bufferedReader.readLine();
        line = bufferedReader.readLine();

        Map<String, Location> textMap = (Map<String, Location>) res.get(MapConstant.TEXT);
        // 读取规则
        while (!MapConstant.PEOPLE.equalsIgnoreCase(line)) {
            String[] split = line.split("[\\s+ ,]");
            textMap.put(split[0], new Location(Integer.parseInt(split[1]), Integer.parseInt(split[2])));
            line = bufferedReader.readLine();
        }

        Map<String, java.util.List<Location>> peopleMap = (Map<String, List<Location>>) res.get(MapConstant.PEOPLE);
        // 读取people
        while (null != (line = bufferedReader.readLine())) {
            String[] split = line.split("[\\s+ ,]");

            List<Location> orDefault = peopleMap.getOrDefault(split[0], new ArrayList<>());
            orDefault.add(new Location(Integer.parseInt(split[1]), Integer.parseInt(split[2])));
            peopleMap.put(split[0], orDefault);
        }

        return res;
    }



}
